<template>
    <div>
        <!--面包屑导航区-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>品牌列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-button class="add-btn" type="primary" @click="openDialog" size="medium">添加品牌</el-button>
            <div class="search-area">
                <el-input class="search-input" v-model="key" placeholder="请输入内容" size="medium"></el-input>
                <el-button class="search-btn" type="primary" @click="handleSearch" size="medium">搜索</el-button>
            </div>
            <el-table
                    :data="tableData"
                    style="width: 100%">
                <el-table-column
                        align="center"
                        label="id"
                        prop="id">
                </el-table-column>
                <el-table-column
                        align="center"
                        label="名称"
                        prop="name">
                </el-table-column>
                <el-table-column
                        align="center"
                        label="Logo"
                        prop="image">
                    <template v-slot="scope">
                        <img :src="scope.row.image" alt="" width="100" >
                    </template>
                </el-table-column>
                <el-table-column
                        align="center"
                        label="首字母"
                        prop="letter">
                </el-table-column>
                <el-table-column
                        align="center"
                        label="操作">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.row.id)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    class="pagination"
                    align="center"
                    background
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    layout="sizes,prev, pager, next"
                    :current-page=pageNum
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    :total="total">
            </el-pagination>
        </el-card>
        <!--添加对话框-->
        <el-dialog
                title="添加品牌"
                :value="selected"
                :visible.sync="addDialogVisible"
                width="50%"
                @close="addDialogClosed"
                :close-on-click-modal=false>
            <!--内容主体区-->
            <el-form :model="editForm" label-width="70px" ref="addFormRef">
                <el-form-item label="品牌名称" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>

<!--                <el-form-item label="Logo" prop="image">-->
<!--                    <el-input v-model="addForm.image"></el-input>-->
<!--                </el-form-item>-->
                <el-form-item label="Logo" prop="image">
                    <el-upload
                            class="avatar-uploader"
                            name="file"
                            action="http://upload.gker.com/upload/upload"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="首字母" prop="letter">
                    <el-input v-model="addForm.letter"></el-input>
                </el-form-item>

                <el-form-item label="商品类目" prop="categories">
                    <el-cascader
                            ref="cascader"
                            style="width: 100%"
                            :options="addForm.categories"
                            :props="props"
                            clearable></el-cascader>
                </el-form-item>
            </el-form>
            <!--底部-->
            <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addBrand">确 定</el-button>
  </span>
        </el-dialog>

        <!--编辑对话框-->
        <el-dialog
                title="编辑品牌"
                :visible.sync="editDialogVisible"
                width="50%"
                @close="editDialogClosed"
                :close-on-click-modal=false>
            <!--内容主体区-->
            <el-form :model="editForm" label-width="70px" ref="addFormRef">
                <el-form-item label="品牌名称" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                </el-form-item>
                <el-form-item label="Logo" prop="image">
                <el-upload
                        class="avatar-uploader"
                        name="file"
                        action="http://upload.gker.com/upload/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="editForm.image" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                </el-form-item>
                <el-form-item label="首字母" prop="letter">
                    <el-input v-model="editForm.letter"></el-input>
                </el-form-item>

                <el-form-item label="商品类目" prop="categories">
                    <el-cascader

                            ref="cascader"
                            style="width: 100%"
                            :options= "this.editCategory"
                            :props="props"
                            clearable></el-cascader>
                </el-form-item>
            </el-form>
            <!--底部-->
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addBrand">确 定</el-button>
  </span>
        </el-dialog>


    </div>
</template>

<script>
    export default {
        name: "Brands",
        data() {
            return {
                tableData: [],
                key: '',
                pageNum: 1,
                pageSize: 10,
                total: 1000,
                editDialogVisible: false,
                addDialogVisible: false,
                editForm: {},
                addForm: {
                    name: '',
                    image: '',
                    letter: '',
                    categories: []
                },
                props: {
                    multiple: true,
                    label: 'name',
                    children: 'children',
                    value: 'id'
                },
                selected: [],
            //    文件上传
                imageUrl: '',
                editCategory:[]
            }
        },
        methods: {
            async handleEdit(id) {
                this.editDialogVisible = true
                const res = await this.$http.get("/item/brand/getBrandById/" + id)
                this.editForm = res.data.data
                this.imageUrl = res.data.data.image
            },
            handleDelete(index, row) {
                this.$confirm('此操作将永久删除品牌, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const res = await this.$http.get("/item/brand/delBrand/" + row.id)
                    if (res.data.code !== "200") {
                        return this.$message.error('删除失败！错误码:' + res.data.code)
                    }
                    this.$message.success('删除成功')
                    this.getBrandList()
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            async getBrandList() {
                let req = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    key: this.key
                }
                const res = await this.$http.post("/item/brand/getBrandList", req)
                if (res.data.code !== "200") {
                    return this.$message.error('获取失败')
                }
                this.tableData = res.data.data.items
                this.total = res.data.data.total
            },
            handleCurrentChange(val) {
                this.pageNum = val
                this.getBrandList()
            },
            handleSizeChange(val) {
                this.pageSize = val
                this.getBrandList()
            },
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()
                this.addForm = {}
                this.imageUrl = ''
            },
            editDialogClosed() {
                this.$refs.editFormRef.resetFields()
                this.addForm = {}
                this.imageUrl = ''
            },
            //发送请求，新增品牌
            async addBrand() {
                this.selected = [10, 11]
                // console.log(this.$refs.cascader.getCheckedNodes(true))//每个元素的value就是cid
                let {categories, ...reqParam} = this.addForm
                let cids = []
                this.$refs.cascader.getCheckedNodes(true).map(c => {
                    cids.push(c.value)
                })
                reqParam.cids = cids
                console.log(this.selected)

                const res = await this.$http.post("/item/brand/addOrEditBrand",reqParam)
                if (res.data.code!=="200"){
                    return this.$message.error('新增失败！' + res.data.msg)
                }
                this.$message.success("新增成功")
                this.addDialogVisible = false
                this.getBrandList()
            },
            //搜索按钮
            handleSearch() {
                this.getBrandList();
            },
            //打开新增窗口，加载类目树
            async openDialog() {
                this.addDialogVisible = true;
                const res = await this.$http.get("/item/category/getCategoryTreeList")
                const tree = res.data.data
                this.addForm.categories = this.getNewTree(tree);
                this.editCategory = this.addForm.categories
                console.log(this.addForm.categories)
            },
            //去除空的子节点
            getNewTree(arr) {
                return arr.map(item => {
                    if (item.children.length > 0) {
                        this.getNewTree(item.children)
                    } else {
                        delete item.children
                    }
                    return item;
                })
            },
            /*文件上传*/
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
                this.addForm.image = res.data.url

            },
            beforeAvatarUpload(file) {
                // const isJPG = file.type === 'image/jpeg';
                // const isLt2M = file.size / 1024 / 1024 < 2;
                //
                // if (!isJPG) {
                //     this.$message.error('上传头像图片只能是 JPG 格式!');
                // }
                // if (!isLt2M) {
                //     this.$message.error('上传头像图片大小不能超过 2MB!');
                // }
                // return isJPG && isLt2M;
            }

        },
        created() {
            this.getBrandList();
        }
    }
</script>

<style lang="less" scoped>
    .add-btn {
        float: left;
        margin-right: 40px;
        margin-bottom: 15px;
    }

    .search-area {

        float: right;

        .search-input {
            width: 180px;

        }

        .search-btn {
            margin: 0 20px 0 0;
            width: 60px;
            float: right;
        }
    }
    /*文件上传*/
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>